package com.quasar.hpatient.view.personal.register.registerFragment;

import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import com.bigkoo.pickerview.OptionsPickerView;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseFragment;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.httpmodel.DataHeadResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.Aerainfodb;
import com.quasar.hpatient.model.litePalmodel.HospitalInfodb;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.model.operationmodel.AccountInfo;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.onInterface.viewInterface.UiInterface;
import com.quasar.hpatient.presenter.AloneUserPresenter;
import com.quasar.hpatient.view.MainActivity_;
import com.quasar.hpatient.view.personal.register.RegisterEditActivity;
import com.quasar.hpatient.widget.SelectWidget;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import chatui.DemoHelper;
import chatui.cacha.UserCacheManager;
import chatui.db.DemoDBManager;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * author : 许建宏
 * Date: 2017/11/27 0027
 * View:注册手术医院
 */

@EFragment(R.layout.register_hospital_fragment_layout)
public class RegisterHospitalFragment extends BaseFragment  implements UiInterface<DataStateResult> {

    private AloneUserPresenter aloneUserPresenter;
    String userCode=MainAppliaction.getInstance().getUserCode();
    Map<String, String> map = MainAppliaction.getInstance().MsgList();
    //记录医院id
    int HospitalId=0;
    //获取地理信息
    List<Aerainfodb> Geography=new ArrayList<>();
    private List<List<HospitalInfodb>> screenHospitalList = new ArrayList<>();
    List<HospitalInfodb> hospitalInfodbList=MainAppliaction.getInstance().getHospitalInfodbList();
    /**
     * 医院筛选
     */
    List<HospitalInfodb> hospitalInfoDBList=MainAppliaction.getInstance().getHospitalInfodbList();

    @ViewById(R.id.sw_operationday)
    SelectWidget sw_operationday;
    @FragmentArg
    PatientInfoData patient;


    @AfterViews
    void init(){

        initView();
        initData();
    }

    @Click(R.id.tv_next)
    public void tv_next(){

        if(HospitalId==0){
          msg("请输入手术医院");
          return;
        }
        aloneUserPresenter.AloneUserData(ConstantManger.USERHOSPITAL,HospitalId+"",ConstantManger.TABLEOPERATION);
    }

    @Click(R.id.tv_last)
    public void tv_last(){
        RegisterEditActivity.ViewPage(6);
    }

    //跳过
    @Click(R.id.tv_skip)
    public void tv_skip(){
        String userName=MainAppliaction.getInstance().getUserName();
        String userPwd=MainAppliaction.getInstance().getPWd();
        if(userName.length()!=0 && userPwd.length()!=0){
            showDialog();
            PostUserinfo();
        }

    }

    @Click(R.id.sw_operationday)
    public void sw_operationday(){
        ShowPickerView();
    }

    private void ShowPickerView() {// 弹出选择器
        screenHospital();
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                sw_operationday.setText(screenHospitalList.get(options1).get(options2).getName());
                HospitalId=screenHospitalList.get(options1).get(options2).getPrimaryid();
            }
        })

                .setTitleText("医院选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(Geography,screenHospitalList);//三级选择器  ,screenHospitalList
        pvOptions.show();
    }

    //根据省市信息获取医院
    public void screenHospital(){
        Geography.clear();
        Geography.addAll(MainAppliaction.getInstance().Geography());
        int num=Geography.size();
        int size=hospitalInfoDBList.size();
        for(int i=0;i<num;i++){
            ArrayList<HospitalInfodb> options1 = new ArrayList<>();
            for(int z=0;z<size;z++){

                if(Geography.get(i).getPrimary()==hospitalInfoDBList.get(z).getProvinceID()){
                    options1.add(hospitalInfoDBList.get(z));
                }
            }
            screenHospitalList.add(options1);
        }
    }

    @Override
    public void initView() {

        if(patient.getPatientOperationInfo()!=null){

            if(patient.getPatientOperationInfo().getHospitalId()!=0){

                for(int i=0;i<hospitalInfodbList.size();i++){
                    if(hospitalInfodbList.get(i).getPrimaryid()==patient.getPatientOperationInfo().getHospitalId()){
                        sw_operationday.setText(hospitalInfodbList.get(i).getName());
                        HospitalId=patient.getPatientOperationInfo().getHospitalId();
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void initData() {
        aloneUserPresenter=new AloneUserPresenter(this);
    }

    @Override
    public void onViewSuccess(DataStateResult data) {
        if(data.getMsgCode().equals("0x00000000")){
            tv_skip();
        }
    }

    @Override
    public void onViewError(String msg) {
        if(msg!=null){
            msg(msg);
        }
    }

    @Override
    public void onViewRefreshUI() {

    }


    //修改用户信息成功后重新获取个人信息
    public void PostUserinfo(){

        String patientName=patient.getName();
        String phone=patient.getPhone();
        String username="";
        if(patientName!=null && patientName.length()>0){
            username=patientName;
        }else{
            username=phone;
        }


        RetrofitConnection.getRoutineApi()
                .UserInformation(userCode,username)
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .doOnNext(new Consumer<DataHeadResult<PatientInfoData>>() {
                    @Override
                    public void accept(DataHeadResult<PatientInfoData> patientInfoDataDataHeadResult) throws Exception {
                        if(!patientInfoDataDataHeadResult.getMsgCode().equals("0x00000000")){
                            throw new RuntimeException(map.get(patientInfoDataDataHeadResult.getMsgCode()));
                        }
                    }
                })
                .subscribe(new Observer<DataHeadResult<PatientInfoData>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull DataHeadResult<PatientInfoData> patientInfoDataDataHeadResult) {
                        ViseLog.d("onNext"+patientInfoDataDataHeadResult.getData());
                        AccountInfo.saveAccount(getActivity(), patientInfoDataDataHeadResult.getData());
                        logChat(patientInfoDataDataHeadResult.getData(),patientInfoDataDataHeadResult.getData().getBmobUserName());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ViseLog.d("onError"+e.getMessage());
                        dessDialog();
                    }

                    @Override
                    public void onComplete() {
                        ViseLog.d("onComplete");
                    }
                });
    }

    /**
     * 登陆环信
     * @param userName 账号   密码默认为 123456
     */
    public void logChat(final PatientInfoData patientInfoData, final String userName){
        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        EMClient.getInstance().logout(true); //登陆前先退出，保证登陆成功！
        DemoDBManager.getInstance().closeDB();

        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(userName);
        EMClient.getInstance().login(userName,"a123456", new EMCallBack() {

            @Override
            public void onSuccess() {

                Random random=new Random();
                // 登录成功，将用户的昵称头像缓存在本地
                String userId = EMClient.getInstance().getCurrentUser();// 用户环信ID
                //名称
                String nickName;
                if(patientInfoData.getRealName()!=null){
                    nickName=patientInfoData.getRealName();
                }else{
                    nickName=userName;
                }

                String avatarUrl = "";
                if(patientInfoData.getCover()!=null){
                    avatarUrl = RetrofitConnection.PHOTOURL+patientInfoData.getCover();
                }


                UserCacheManager.save(userId, nickName, avatarUrl);

                // ** manually load all local groups and conversation
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                String nick = "";
                try {
                    nick = EMClient.getInstance().pushManager().getPushConfigsFromServer().getDisplayNickname();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(nickName);
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }

                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

                Intent intent = new Intent(getActivity(),
                        MainActivity_.class);
                startActivity(intent);
                dessDialog();
            }

            @Override
            public void onProgress(int progress, String status) {
                ViseLog.d("login: onProgress"+status);
                dessDialog();
            }

            @Override
            public void onError(final int code, final String message) {
                ViseLog.d("login: onError:"+code+"+++"+message);
                dessDialog();
            }
        });

    }
}
